const path = require('node:path')
const fastcsv = require('fast-csv');
const fs = require('fs')
const csv = require('csv-parser')

const CSV_FILENAME = path.join(__dirname, 'data_origin.csv')

function setStatus(req) {
  const newRows = []
  const { ids_to_update, newStatus } = req

  fs.createReadStream(CSV_FILENAME)
  .pipe(csv())
  .on('data', (row) => {
    if (!ids_to_update || ids_to_update.includes(row['编号'])) {
      row['状态'] = newStatus
    }
    newRows.push(row)
  })
  .on('end', () => { 
    const csvStream = fastcsv.format({ headers: true });
    csvStream.pipe(fs.createWriteStream(CSV_FILENAME,{
      flags: 'w', 
      encoding: 'utf8',
      autoClose: true
    }));

    newRows.forEach((row) => {
      csvStream.write(row);
    });
    
    csvStream.end();
  })
  .on('error', (err) => {
    console.error(`读取文件时出错: ${err.message}`);
  });
}


// setStatus({ ids_to_update: '', newStatus: '0' })

